import React, { useCallback, useEffect } from 'react';
import { Modal, Button, Form, Input, Space } from 'antd';

const formWrap = {
  labelCol: { span: 5 },
  wrapperCol: { span: 16 },
};

const wrapperCol = { offset: 8, span: 16 };

interface AddOrEditProps {
  isModalVisible: boolean;
  onCancelWrite: () => void;
  flag: string;
  onSubmit: (valuse: any) => void;
  userData: any;
}

const AddOrEdit: React.FC<AddOrEditProps> = ({
  isModalVisible,
  onCancelWrite,
  flag,
  onSubmit,
  userData,
}) => {
  const [form] = Form.useForm();
  const handleCancel = useCallback(() => {
    onCancelWrite();
    form.resetFields();
  }, [onCancelWrite, form]);

  const handleFinsh = useCallback(
    (values) => {
      onSubmit(values);
    },
    [onSubmit],
  );

  const handleReset = useCallback(() => {
    form.resetFields();
  }, [form]);

  useEffect(() => {
    if (flag === 'edit') {
      form.setFieldsValue(userData);
    } else if (flag === 'add') {
      form.resetFields();
    }
  }, [flag, form, userData]);

  return (
    <Modal
      title={flag === 'add' ? '新增用户' : '编辑用户'}
      visible={isModalVisible}
      onCancel={handleCancel}
      footer={null}
      forceRender={true}
      destroyOnClose={true}
    >
      <Form form={form} {...formWrap} onFinish={handleFinsh} preserve={false}>
        <Form.Item
          label="昵称"
          name="name"
          rules={[{ required: true, message: '请输入昵称' }]}
        >
          <Input placeholder="请输入昵称" />
        </Form.Item>

        <Form.Item
          label="邮箱"
          name="email"
          rules={[{ required: true, message: '请输入邮箱' }]}
        >
          <Input placeholder="请输入邮箱" />
        </Form.Item>

        {flag !== 'edit' ? (
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password placeholder="请输入密码" />
          </Form.Item>
        ) : null}

        <Form.Item wrapperCol={wrapperCol}>
          <Space>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
            <Button onClick={handleReset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddOrEdit;
